package com.charlie.db;

import com.charlie.beans.ShipmentOrder;
import com.charlie.sessions.Cart;
import java.lang.reflect.Field;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.annotation.PostConstruct;
import javax.ejb.EJB;
import javax.ejb.Singleton;
import javax.ejb.Startup;
import javax.persistence.Column;
import javax.persistence.Table;

/**
 *
 * @author Vitaliy Mostipaka <imprtat@gmail.com>
 */
@Singleton
@Startup
public class DBInfo {
    
    @EJB
    DAOLocal dao;
   
    @PostConstruct
    public void init() {
        int maxCost = getFieldMaxValue(ShipmentOrder.class, "cost");
        Cart.setMaxCost(maxCost);
    }
    
    private <A> int getFieldMaxValue(Class<A> type, String field) {
        try {
            Table table = type.getAnnotation(Table.class);
            Field filed = type.getDeclaredField(field);
            Column column = filed.getAnnotation(Column.class);
            FieldDescription desc = dao.getFildsDescription(table.name(), column.name());
            if (desc != null) {
                return (int) Math.pow(10f, (float) desc.getPrecision());
            }
        } catch (NoSuchFieldException ex) {
            Logger.getLogger(DBInfo.class.getName()).log(Level.SEVERE, null, ex);
        } catch (SecurityException ex) {
            Logger.getLogger(DBInfo.class.getName()).log(Level.SEVERE, null, ex);
        }
        return 0;
    }
}
